package com.orangelife.mobile.parkingcard.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;

import com.common.jump.CommonJumper;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.google.gson.reflect.TypeToken;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ParkingCardURL;
import com.orangelife.mobile.parkingcard.activity.ApplyForParkingCardBeginActivity;
import com.orangelife.mobile.parkingcard.adapter.HaveCardListAdapter;
import com.orangelife.mobile.parkingcard.bean.ParkingInfomation;
import com.orangelife.mobile.parkingcard.biz.ParkingCardHttpBiz;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;

/**
 * Created by yyx
 * on 2015/11/17.
 */
public class PublicFragment extends Fragment implements HaveCardListAdapter.OnLongClickListenerInterface {

    /** 带刷新的listview */
    private PullToRefreshListView lvList;
    /** 添加停车卡按钮 */
    private Button btnSubmit;
    private View view;

    /** 分辨是刷新还是加载更多 */
    private int flags = 1;
    /** 一页中数据的条数，初始设置为7条 */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /** 初始页，初始化为第一页 */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    private Handler mHandler;
    private List<Map<String, Object>> list2;
    private List<Map<String, Object>> list;
    private HaveCardListAdapter adapter = null;
    /** 停车卡ID */
    private String parkingCardID = "";
    /** 车牌号 */
    private String carNumber = "";

    private Dialog dialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_parking_public,
                    null);
        }
        initeView();
        findView();
        /*
         * 缓存的rootView需要判断是否已经被加过parent，
		 * 如果有parent需要从parent删除，要不然会发生这个view已经有parent的错误。
		 */
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        ButterKnife.bind(this, view);
        return view;
    }

    /***
     * 初始化
     */
    private void initeView() {
        lvList = (PullToRefreshListView) view.findViewById(R.id.lvList);
        btnSubmit = (Button) view.findViewById(R.id.btnSubmit);
    }

    /***
     * 初始化赋值
     */
    private void findView() {
        list = ParkingInfomation.getListPublic();
        mHandler = new Handler();
        pullListView();
        setAdapter();
        lvList.setPullLoadEnable(true);
        btnSubmit.setOnClickListener(listener);
        lvList.setOnItemLongClickListener(longListener);
    }

    public void updateUI() {
        list = ParkingInfomation.getListPublic();
        mHandler = new Handler();
        setAdapter();
        pullListView();
        lvList.setPullLoadEnable(true);
        btnSubmit.setOnClickListener(listener);
        lvList.setOnItemLongClickListener(longListener);
    }

    /**
     * 为listview设置值
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private void setAdapter() {
        if (list == null) {
            list = new ArrayList<>();
        }
        if (list2 == null) {
            list2 = new ArrayList<>();
        }
        adapter = new HaveCardListAdapter(getActivity(), list, this);
        lvList.setAdapter(adapter);
    }

    //    private void getParkingCard(int pageSize,int pageNo){
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("pageSize", pageSize);
//        map.put("pageIndex", pageNo);
//        Map<String, Object> rootMap = new HashMap<String, Object>();
//        rootMap.put("map", map);
////        rootMap.put("url", Constant.URL_PARKCARD_LIST);
//        rootMap.put("url", ParkingCardURL.PARKCARD_LIST);
//        rootMap.put("wat", 0);
//        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
//    }
    private void getParkingCard(int pageSize, int pageNo) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("pageSize", String.valueOf(pageSize));
        map.put("pageIndex", String.valueOf(pageNo));
        VolleyHttpUtil.getInstance().getWithCallback(ParkingCardURL.PARKCARD_LIST, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                list2 = OrangeDataHandler.getListFromJsonWithPageEntity(
                        jsonObject, new TypeToken<List<Map<String, Object>>>() {
                        }.getType(), adapter, dialog);
                updateListView(list2);
            }
        });
    }


    /**
     * 点击事件的监听器
     */
    public View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.btnSubmit:
                    IntentHelper.getInstances().getIntent(getActivity(), ApplyForParkingCardBeginActivity.class);
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 长按删除
     */
    public AdapterView.OnItemLongClickListener longListener = new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                       int position, long id) {
            if (position > list.size()) {
                return false;
            }
            parkingCardID = list.get(position - 1).get("id").toString();
            carNumber = list.get(position - 1).get("num_plate").toString();
            String status = list.get(position - 1).get("status").toString();
            if ("0".equals(status)) {
                isDeleteDialog();
            }
            return true;
        }
    };

    /** 弹出对话框 */
    private void isDeleteDialog() {
        String message = "确定要删除" + carNumber + "吗？";
        final ConfirmDialog confirmDialog = new ConfirmDialog(
                getActivity(), getResources().getString(
                R.string.warm_prompt), message, getResources().getString(
                R.string.cancel), getResources().getString(
                R.string.sure));
        confirmDialog.show();
        confirmDialog
                .setClicklistener(new ConfirmDialog.ClickListenerInterface() {

                    @Override
                    public void doLeft() {
                        confirmDialog.dismiss();
                    }

                    @Override
                    public void doRight() {
                        confirmDialog.dismiss();
                        deleteParkingCard();

                    }
                });
    }

    /**
     * 删除消息
     */
//    @SuppressWarnings("deprecation")
//    private void deleteParkingCard() {
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("{cardID}", parkingCardID);
//        Map<String, Object> rootMap = new HashMap<String, Object>();
//        rootMap.put("map", map);
//        rootMap.put("url", Constant.URL_PARKCARD_DELETE);
//        rootMap.put("wat", 1);
//        new JSONRequest(JSONRequest.DELETE, rootMap, handler,
//                HttpUtil.ACTION_JSON);
//    }
    @SuppressWarnings("deprecation")
    private void deleteParkingCard() {
        ParkingCardHttpBiz.delPakingCard(parkingCardID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    pageNo = 1;
                    flags = 1;
                    getParkingCard(pageSize, pageNo);
                    onLoad();
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    ToastHelper.getInstance()._toast("删除成功");
                } else {
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast("删除失败");
                }
            }
        });
    }


    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvList.setXListViewListener(new PullToRefreshListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @SuppressWarnings("unchecked")
                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        getParkingCard(pageSize, pageNo);
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @SuppressWarnings("unchecked")
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        getParkingCard(pageSize, pageNo);
                        onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvList.stopRefresh();
        lvList.stopLoadMore();
        lvList.setRefreshTime(new Date().toLocaleString());
    }

    /**
     * 处理获得的数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    list2 = JsonReponseHandler.getListFromJson(
                            String.valueOf(msg.obj), adapter, dialog);
                    updateListView(list2);
                    break;
                case 1:
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    if (errInfo.equals("OK")) {
                        DialogHelper.closeDialog(dialog);
                        pageNo = 1;
                        flags = 1;
                        getParkingCard(pageSize, pageNo);
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                        ToastHelper.getInstance()._toast("删除成功");
                    } else {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast("删除失败");
                    }
                    break;
                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                case 1011:
                    DialogHelper.closeDialog(dialog);
                    CommonJumper.jumpToLoginWhenExitWithClear(getActivity());
                    break;

                default:
                    break;
            }
        }

    };

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    @SuppressWarnings({"unchecked"})
    private void updateListView(List<Map<String, Object>> list2) {

        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                if (flags == 1) {
                    list.clear();
                    lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                } else {
                    lvList.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            } else {
                if (flags == 1) {
                    list.clear();
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                } else {
                    lvList.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                }
            }
        } else {
            lvList.setPullLoadEnable(false);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void delete(int position, Map<String, Object> map) {
        /*parkingCardID = list.get(position).get("id").toString();
        carNumber = list.get(position).get("num_plate").toString();
        String status = list.get(position).get("status").toString();
        if("0".equals(status)){
            isDeleteDialog();
        }*/
    }
}
